package com.android.UrbanRemix;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.TimeZone;

import com.android.UrbanRemix.HttpFileUploader;
import com.android.UrbanRemix.UrbanRemix_New;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ArrayAdapter;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.view.Menu;

import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class UploadFunctionality extends ListActivity {
	String username;
	String password;
	String muploadUrlString;
	String filestoupload;
	String taggedFileName;
	String files[];
	String tags;
	private MediaPlayer mp;
	public static final String TAGS_XML = "http://urbanremix.lcc.gatech.edu/tags_xml.php";
	public static final String MUPLOAD = "http://urbanremix.lcc.gatech.edu/mupload.php";
	HttpFileUploader qUploader;
	Request rq;
	private String folderPath, tempFolderPath, queueFolderPath,
			userChoiceFolderPath;
	private File folder, tempFolder, queueFolder, userChoiceFolder;
	int choice;
	static final int LOGIN = 0;
	static final int EDITLOGIN = 1;
	static final int CHOOSE_TAGS_REQUEST = 2;
	public static final String MYPREFS = "mySharedPreferences";
	static final int RECORD = 0;
	static final int TAKE_SNAPSHOT = 1;
	static final int REVIEW_QUEUE = 2;
	static final int EXIT = 3;
	boolean playing = false;
	public String flag, flag_edit;
	public String wavname;
	public String wavnameanddate;
	private String externalMediaPath;
	Context myContext;
	Button uploadButton, loginButton, editButton, addTagsButton, backButton,
			uploadRedirectButton, editRedirectButton, doneButton;
	Button changeNameButton, previewButton, doneRenameButton,
			cancelRenameButton;
	TextView user_name_box;
	TextView password_box;
	TextView rename_box;
	TextView upload_queue;
	ListView listView;
	ImageView imagePreview;
	Bitmap bmImg;
	int add_tags_for_image = 1;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.uploadqueue);

		imagePreview = (ImageView) findViewById(R.id.ImagePreview);
		uploadButton = (Button) findViewById(R.id.Upload);
		loginButton = (Button) findViewById(R.id.Login);
		editButton = (Button) findViewById(R.id.Edit);
		uploadRedirectButton = (Button) findViewById(R.id.UploadRedirect);
		editRedirectButton = (Button) findViewById(R.id.EditRedirect);
		addTagsButton = (Button) findViewById(R.id.AddTags);
		changeNameButton = (Button) findViewById(R.id.ChangeName);
		previewButton = (Button) findViewById(R.id.Preview);
		backButton = (Button) findViewById(R.id.Back);
		doneButton = (Button) findViewById(R.id.Done);
		doneRenameButton = (Button) findViewById(R.id.DoneRename);
		cancelRenameButton = (Button) findViewById(R.id.CancelRename);
		externalMediaPath = Environment.getExternalStorageDirectory()
				.getAbsolutePath();
		user_name_box = (TextView) findViewById(R.id.UserName);
		password_box = (TextView) findViewById(R.id.Password);
		upload_queue = (TextView) findViewById(R.id.text1);
		rename_box = (TextView) findViewById(R.id.Rename);

		imagePreview.setVisibility(View.GONE);
		upload_queue.setVisibility(View.GONE);
		loginButton.setVisibility(View.GONE);
		addTagsButton.setVisibility(View.GONE);
		backButton.setVisibility(View.GONE);
		user_name_box.setVisibility(View.GONE);
		password_box.setVisibility(View.GONE);
		rename_box.setVisibility(View.GONE);
		doneRenameButton.setVisibility(View.GONE);
		cancelRenameButton.setVisibility(View.GONE);
		uploadButton.setVisibility(View.GONE);
		editButton.setVisibility(View.GONE);
		backButton.setVisibility(View.GONE);

		doneButton.setVisibility(View.GONE);
		changeNameButton.setVisibility(View.GONE);
		previewButton.setVisibility(View.GONE);

		folderPath = externalMediaPath + "/urbanremix";
		tempFolderPath = folderPath + "/temp";
		queueFolderPath = folderPath + "/queue";
		userChoiceFolderPath = folderPath + "/userchoice";

		queueFolder = new File(queueFolderPath);
		folder = new File(folderPath);
		tempFolder = new File(tempFolderPath);
		userChoiceFolder = new File(userChoiceFolderPath);

		myContext = this;
		qUploader = new HttpFileUploader(this, UploadFunctionality.MUPLOAD);

		File[] userChoiceFiles = userChoiceFolder.listFiles();
		int t = userChoiceFiles.length;
		if (t <= 0) {
			Request.notification(myContext, "Error", "No files to display");
			finish();
		}

		uploadButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				choice = 0;
				loadPreferences();
				int mode = Activity.MODE_PRIVATE;
				SharedPreferences mySharedPreferences = getSharedPreferences(
						"mySharedPreferences", mode);
				int should_add_tags_be_displayed = 0;
				ListView lv = getListView();

				for (int i = 0; i < lv.getCount(); i++) {
					if (lv.isItemChecked(i)) {
						should_add_tags_be_displayed = 1;
						break;
					} else {
						should_add_tags_be_displayed = 0;
					}
				}

				if (should_add_tags_be_displayed == 1) {

					flag = mySharedPreferences.getString("flag", "");
					flag_edit = mySharedPreferences.getString("flag_edit", "");
					if (flag.equals("0") && flag_edit.equals("0")) {
						loginButton.setVisibility(View.VISIBLE);
						user_name_box.setVisibility(View.VISIBLE);
						password_box.setVisibility(View.VISIBLE);
						uploadButton.setVisibility(View.GONE);
						editButton.setVisibility(View.GONE);
						listView.setVisibility(View.GONE);
						uploadRedirectButton.setVisibility(View.GONE);
						editRedirectButton.setVisibility(View.GONE);
						backButton.setVisibility(View.GONE);
						doneButton.setVisibility(View.GONE);
						upload_queue.setVisibility(View.GONE);

					} else {
						// check if user name or password is entered. If yes
						// then call upload functionality directly else call
						// those and then this.
						filesToString();
						createListFromFiles();
						upload_queue.setVisibility(View.VISIBLE);
						listView = getListView();
						listView.setVisibility(View.VISIBLE);
						upload_functionality();
						doneButton.setVisibility(View.GONE);
						editButton.setVisibility(View.GONE);
						uploadRedirectButton.setVisibility(View.GONE);
						editRedirectButton.setVisibility(View.GONE);
						backButton.setVisibility(View.VISIBLE);
						doneButton.setVisibility(View.GONE);
					}
				} else {
					Request.notification(myContext, "",
							"Please select a file to Upload");

				}
			}
		});

		backButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				backButton.setVisibility(View.GONE);
				addTagsButton.setVisibility(View.GONE);
				uploadRedirectButton.setVisibility(View.VISIBLE);
				editRedirectButton.setVisibility(View.VISIBLE);
				uploadButton.setVisibility(View.GONE);
				editButton.setVisibility(View.GONE);
				listView = getListView();
				listView.setVisibility(View.GONE);
				doneButton.setVisibility(View.GONE);
				changeNameButton.setVisibility(View.GONE);
				previewButton.setVisibility(View.GONE);
				upload_queue.setVisibility(View.GONE);

			}
		});

		doneButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				doneButton.setVisibility(View.GONE);
				addTagsButton.setVisibility(View.GONE);
				uploadButton.setVisibility(View.GONE);
				editButton.setVisibility(View.VISIBLE);
				backButton.setVisibility(View.VISIBLE);
				editRedirectButton.setVisibility(View.GONE);
				uploadRedirectButton.setVisibility(View.GONE);
				changeNameButton.setVisibility(View.GONE);
				previewButton.setVisibility(View.GONE);
				upload_queue.setVisibility(View.VISIBLE);
				// bmImg.recycle();
				imagePreview.setVisibility(View.GONE);
				createListFromFiles();
				listView = getListView();
				listView.setItemsCanFocus(false);
				listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
				listView.setVisibility(View.VISIBLE);

			}
		});

		loginButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				savePreferences();
				if (choice == 0) {
					Intent intent = new Intent(myContext,
							CheckUserNamePassword.class);
					startActivityForResult(intent, LOGIN);
				}
				if (choice == 1) {
					Intent intent = new Intent(myContext,
							CheckUserNamePassword.class);
					startActivityForResult(intent, EDITLOGIN);
				}
			}

		});

		uploadRedirectButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				upload_queue.setVisibility(View.VISIBLE);
				createListFromFiles();

				listView = getListView();

				listView.setItemsCanFocus(false);
				listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

				uploadButton.setVisibility(View.VISIBLE);
				listView.setVisibility(View.VISIBLE);
				uploadRedirectButton.setVisibility(View.GONE);
				editRedirectButton.setVisibility(View.GONE);
				backButton.setVisibility(View.VISIBLE);
				doneButton.setVisibility(View.GONE);
			}

		});

		editRedirectButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				doneButton.setVisibility(View.GONE);
				editButton.setVisibility(View.VISIBLE);
				backButton.setVisibility(View.VISIBLE);
				editRedirectButton.setVisibility(View.GONE);
				uploadRedirectButton.setVisibility(View.GONE);
				upload_queue.setVisibility(View.VISIBLE);
				createListFromFiles();

				listView = getListView();
				listView.setItemsCanFocus(false);
				listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
				listView.setVisibility(View.VISIBLE);

			}

		});

		editButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				choice = 1;
				loadPreferences();
				int mode = Activity.MODE_PRIVATE;
				SharedPreferences mySharedPreferences = getSharedPreferences(
						"mySharedPreferences", mode);
				int should_add_tags_be_displayed = 0;
				ListView lv = getListView();
				String tempstring = "";
				String ext = "";
				for (int i = 0; i < lv.getCount(); i++) {
					if (lv.isItemChecked(i)) {
						tempstring = tempstring + files[i];

						if (tempstring.length() > 1)
							ext = tempstring.substring(tempstring
									.lastIndexOf(".") + 1, tempstring.length());

						if (ext.equals("jpg")) {
							/*
							 * Request.notification(myContext, "Debug", ext +
							 * "extension and filename" + tempstring);
							 */
							add_tags_for_image = 0;
						} else
							add_tags_for_image = 1;
						should_add_tags_be_displayed = 1;
						break;
					} else {
						should_add_tags_be_displayed = 0;
					}
				}

				if (should_add_tags_be_displayed == 1) {

					flag = mySharedPreferences.getString("flag", "");
					flag_edit = mySharedPreferences.getString("flag_edit", "");

					if (flag.equals("0") && flag_edit.equals("0")) {
						loginButton.setVisibility(View.VISIBLE);
						user_name_box.setVisibility(View.VISIBLE);
						password_box.setVisibility(View.VISIBLE);
						uploadButton.setVisibility(View.GONE);
						listView.setVisibility(View.GONE);
						editButton.setVisibility(View.GONE);
						editRedirectButton.setVisibility(View.GONE);
						uploadRedirectButton.setVisibility(View.GONE);
						doneButton.setVisibility(View.GONE);
						backButton.setVisibility(View.GONE);
						upload_queue.setVisibility(View.GONE);
					} else {
						// check if user name or password is entered. If yes
						// then call upload functionality directly else call
						// those and then this.

						// Request.notification( myContext ,"Audio",
						// "Audio Stored: "+wavio.getWavFileName());
						// myContext.toggleButtonAvailability(true);
						if (add_tags_for_image == 1) {
							addTagsButton.setVisibility(View.VISIBLE);
						} else {
							addTagsButton.setVisibility(View.GONE);
						}
						listView.setVisibility(View.GONE);
						upload_queue.setVisibility(View.GONE);
						editButton.setVisibility(View.GONE);
						uploadButton.setVisibility(View.GONE);

						changeNameButton.setVisibility(View.VISIBLE);
						previewButton.setVisibility(View.VISIBLE);
						doneButton.setVisibility(View.VISIBLE);
						backButton.setVisibility(View.GONE);
					}
				} else {
					Request.notification(myContext, "",
							"Please select a file to Edit");
				}
			}

		});

		addTagsButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				Intent intent = new Intent(myContext, TagSelection.class);
				startActivityForResult(intent, CHOOSE_TAGS_REQUEST);

			}
		});

		changeNameButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				rename_box.setVisibility(View.VISIBLE);
				doneRenameButton.setVisibility(View.VISIBLE);
				cancelRenameButton.setVisibility(View.VISIBLE);
				changeNameButton.setVisibility(View.GONE);
				previewButton.setVisibility(View.GONE);
				doneButton.setVisibility(View.GONE);
				addTagsButton.setVisibility(View.GONE);

			}
		});

		cancelRenameButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				rename_box.setVisibility(View.GONE);
				doneRenameButton.setVisibility(View.GONE);
				cancelRenameButton.setVisibility(View.GONE);
				changeNameButton.setVisibility(View.VISIBLE);
				previewButton.setVisibility(View.VISIBLE);
				doneButton.setVisibility(View.VISIBLE);
				if (add_tags_for_image == 1) {
					addTagsButton.setVisibility(View.VISIBLE);
				} else {
					addTagsButton.setVisibility(View.GONE);
				}
			}
		});

		doneRenameButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				renamefile_functionality();
				rename_box.setVisibility(View.GONE);
				doneRenameButton.setVisibility(View.GONE);
				cancelRenameButton.setVisibility(View.GONE);
				changeNameButton.setVisibility(View.VISIBLE);
				addTagsButton.setVisibility(View.GONE);
				previewButton.setVisibility(View.GONE);
				doneButton.setVisibility(View.VISIBLE);

			}
		});

		previewButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				preview_File_Functionality();

			}
		});

	}

	public boolean onCreateOptionsMenu(Menu menu) {

		menu.add(0, RECORD, 0, "Record");

		menu.add(0, TAKE_SNAPSHOT, 0, "Take Snapshot");

		menu.add(0, REVIEW_QUEUE, 0, "Review Upload Queue");

		menu.add(0, EXIT, 0, "Exit");

		return true;

	}

	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {

		case RECORD:
			Intent intent = new Intent(myContext, PostSnapShot.class);
			startActivity(intent);

			return true;

		case TAKE_SNAPSHOT:
			intent = new Intent(myContext, PostSnapShot.class);
			startActivity(intent);

			return true;

		case REVIEW_QUEUE:

			intent = new Intent(myContext, UploadFunctionality.class);
			startActivity(intent);

			return true;

		case EXIT:
			// Request.notification(myContext, "Image", "X pressed");

			return true;

		}

		return false;

	}

	protected void savePreferences() {
		int mode = Activity.MODE_PRIVATE;
		SharedPreferences mySharedPreferences = getSharedPreferences(MYPREFS,
				mode);

		SharedPreferences.Editor editor = mySharedPreferences.edit();

		editor.putString("username", user_name_box.getText().toString());
		editor.putString("password", password_box.getText().toString());

		editor.commit();
	}

	// -------------
	// called when the app launches -- i.e., onCreate() --
	// to retrieve the username and password from a previous session

	public void loadPreferences() {
		int mode = Activity.MODE_PRIVATE;
		SharedPreferences mySharedPreferences = getSharedPreferences(
				"mySharedPreferences", mode);

		username = mySharedPreferences.getString("username", "");
		password = mySharedPreferences.getString("password", "");

		user_name_box.setText(username);
		password_box.setText(password);
	}

	// ------------
	// when the app terminates, remember the preferences (i.e., username and
	// password)
	// for next time...

	@Override
	protected void onDestroy() {
		savePreferences();
		super.onDestroy();
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == LOGIN) {
			Bundle b;
			try {
				b = data.getExtras();

				String returnMessage = b
						.getString("com.android.urbanremix.ReturnMessage");
				// TextView tv = (TextView) findViewById(R.id.statusbar);
				Request.notification(myContext, "Message", returnMessage);
				// tv.setVisibility(1);
				// tv.setText(returnMessage);

			} catch (NullPointerException e) {
			}

			switch (resultCode) {
			case RESULT_OK:
				b = data.getExtras();
				TextView tv = (TextView) findViewById(R.id.statusbar);
				String returnMessage = b
						.getString("com.android.urbanremix.ReturnMessage");
				savePreferences();
				tv.setVisibility(1);
				tv.setText(returnMessage);

				upload_queue.setVisibility(View.VISIBLE);
				uploadButton.setVisibility(View.VISIBLE);
				backButton.setVisibility(View.VISIBLE);
				editButton.setVisibility(View.GONE);
				loginButton.setVisibility(View.GONE);
				user_name_box.setVisibility(View.GONE);
				password_box.setVisibility(View.GONE);

				int mode = Activity.MODE_PRIVATE;
				SharedPreferences mySharedPreferences = getSharedPreferences(
						"mySharedPreferences", mode);

				SharedPreferences.Editor editor = mySharedPreferences.edit();
				editor.putString("flag", "1");
				editor.commit();
				filesToString();
				createListFromFiles();
				listView = getListView();
				listView.setVisibility(View.VISIBLE);
				upload_functionality();

				break;

			case RESULT_CANCELED:

				try {
					b = data.getExtras();
					returnMessage = b
							.getString("com.android.urbanremix.ReturnMessage");
					Request.notification(myContext, "Message", returnMessage);

				}
				// if the cancellation didn't return an error message -- e.g.,
				// if the user
				// just clicked the back button on the phone -- then don't
				// display anything in
				// the status bar.
				catch (NullPointerException e) {
				}

			default:
				break;
			}
		} else if (requestCode == CHOOSE_TAGS_REQUEST) {
			Bundle b;
			try {
				b = data.getExtras();

				String returnMessage = b
						.getString("com.android.urbanremix.ReturnMessage");
				TextView tv = (TextView) findViewById(R.id.statusbar);
				// Request.notification( myContext ,"Message",returnMessage);
				// tv.setTextColor(11);
				tv.setVisibility(1);
				tv.setText(returnMessage);

			} catch (NullPointerException e) {
			}

			// ------------
			// if the TagSelection's return message is "OK" (i.e., the user hit
			// the "upload"
			// button), then we assume we've been passed a comma-separated
			// string of tags.
			// we then try to get the most current location, save the info
			// related to this file
			// in our saved preferences (which will persist even if the app is
			// terminated),
			// copy the temporary files -- wav and jpg alike -- into the queue
			// for uploading,
			// start the uploader thread (if it hasn't started already), and
			// reset the state
			// of the buttons.

			switch (resultCode) {
			case RESULT_OK:
				b = data.getExtras();
				tags = b.getString("com.android.urbanremix.Tags");
				int mode = Activity.MODE_PRIVATE;
				SharedPreferences mySharedPreferences = getSharedPreferences(
						"mySharedPreferences", mode);
				filesToEdit();

				/*
				 * createListFromFiles();
				 * 
				 * listView = getListView(); listView.setItemsCanFocus(false);
				 * listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
				 * listView.setVisibility(View.VISIBLE);
				 */

				break;

			case RESULT_CANCELED:
				TextView tv = (TextView) findViewById(R.id.statusbar);

				try {
					b = data.getExtras();
					String returnMessage = b
							.getString("com.android.urbanremix.ReturnMessage");
					// Request.notification( myContext
					// ,"Message",returnMessage);
					tv.setText(returnMessage);
				}
				// if the cancellation didn't return an error message -- e.g.,
				// if the user
				// just clicked the back button on the phone -- then don't
				// display anything in
				// the status bar.
				catch (NullPointerException e) {
				}

			default:
				break;
			}
		}

		else if (requestCode == EDITLOGIN) {

			Bundle b;
			try {
				b = data.getExtras();

				String returnMessage = b
						.getString("com.android.urbanremix.ReturnMessage");
				// TextView tv = (TextView) findViewById(R.id.statusbar);
				Request.notification(myContext, "Message", returnMessage);
				// tv.setVisibility(1);
				// tv.setText(returnMessage);

			} catch (NullPointerException e) {
			}

			switch (resultCode) {
			case RESULT_OK:
				b = data.getExtras();
				TextView tv = (TextView) findViewById(R.id.statusbar);
				String returnMessage = b
						.getString("com.android.urbanremix.ReturnMessage");
				savePreferences();
				tv.setVisibility(1);
				tv.setText(returnMessage);

				// uploadButton.setVisibility(View.VISIBLE);

				int mode = Activity.MODE_PRIVATE;
				SharedPreferences mySharedPreferences = getSharedPreferences(
						"mySharedPreferences", mode);

				SharedPreferences.Editor editor = mySharedPreferences.edit();
				editor.putString("flag_edit", "1");
				editor.commit();

				tv.setVisibility(1);
				tv.setText(returnMessage);
				if (add_tags_for_image == 1)
					addTagsButton.setVisibility(View.VISIBLE);
				else
					addTagsButton.setVisibility(View.GONE);

				changeNameButton.setVisibility(View.VISIBLE);
				previewButton.setVisibility(View.VISIBLE);

				doneButton.setVisibility(View.VISIBLE);
				editButton.setVisibility(View.GONE);
				loginButton.setVisibility(View.GONE);
				user_name_box.setVisibility(View.GONE);
				password_box.setVisibility(View.GONE);

				break;

			case RESULT_CANCELED:

				try {
					b = data.getExtras();
					returnMessage = b
							.getString("com.android.urbanremix.ReturnMessage");
					Request.notification(myContext, "Message", returnMessage);

				}
				// if the cancellation didn't return an error message -- e.g.,
				// if the user
				// just clicked the back button on the phone -- then don't
				// display anything in
				// the status bar.
				catch (NullPointerException e) {
				}

			default:
				break;
			}
		}

	}

	public void createListFromFiles() {
		File[] userChoiceFiles = userChoiceFolder.listFiles();
		int t = userChoiceFiles.length;
		files = new String[t];

		// ((android.widget.Button)findViewById(R.id.Start)).setText(h);
		int i = 0;
		while (i < t) {

			files[i] = userChoiceFiles[i].getName();
			i++;
		}
		java.util.Arrays.sort(files, java.util.Collections.reverseOrder());
		setListAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_multiple_choice, files));
	}

	private void filesToString() {
		ListView lv = getListView();
		String tempstring = new String();
		for (int i = 0; i < lv.getCount(); i++) {
			if (lv.isItemChecked(i)) {
				tempstring = tempstring + files[i] + ",";

			}
		}

		if (tempstring.length() > 1)
			tempstring = tempstring.substring(0, tempstring.lastIndexOf(","));
		filestoupload = tempstring;
		String temp[] = filestoupload.split(",");
		qUploader.setUploading(false);
		// Request.notification( myContext ,"Image", "just befor for" +
		// tempstring);

		// Request.notification( myContext ,"Image", "just befor for");
		for (int i = 0; i < temp.length; i++) {

			File[] userChoiceFiles = userChoiceFolder.listFiles();
			int t = userChoiceFiles.length;

			// Request.notification( myContext ,"Image", "inside first for");
			for (int j = 0; j < t; j++) {
				// Request.notification( myContext ,"Image",
				// "inside second for");
				try {
					// Request.notification( myContext ,"Image",
					// "just before if");
					FileChannel channel = new RandomAccessFile(
							userChoiceFiles[j], "rw").getChannel();
					FileLock lock = channel.lock();
					// Request.notification( myContext ,"Image",
					// "just before if");
					try {
						lock = channel.tryLock();
					} catch (Exception e) {
					}

					if (userChoiceFiles[j].getName().equals(temp[i])) {
						userChoiceFiles[j].renameTo(new File(queueFolder
								.getAbsoluteFile()
								+ "/" + userChoiceFiles[j].getName()));
						// Request.notification( myContext ,"Image", "inside if"
						// + temp[i] +" and " + userChoiceFiles[j]);
						break;
					} else {
						// Request.notification( myContext ,"Image", "in else" +
						// temp[i] +" and " + userChoiceFiles[j]);
					}
					lock.release();
				} catch (Exception e) {
				}
			}
		}
		qUploader.setUploading(true);

	}

	private void filesToEdit() {
		ListView lv = getListView();
		String tempstring = new String();

		for (int i = 0; i < lv.getCount(); i++) {
			if (lv.isItemChecked(i)) {
				tempstring = tempstring + files[i] + ",";

			}
		}

		if (tempstring.length() > 1)
			tempstring = tempstring.substring(0, tempstring.lastIndexOf("."));

		// Request.notification(myContext, "Welcome", "checking tags"+
		// tempstring);
		// String filename = tempstring.substring(0,
		// tempstring.lastIndexOf("."));
		String latString = getFileLatitude(tempstring);
		String lngString = getFileLongitude(tempstring);
		String accString = getFileAccuracy(tempstring);
		registerFilePrefs(tempstring, latString, lngString, accString, tags);

	}

	public void renamefile_functionality() {
		ListView lv = getListView();
		String tempstring = "";
		String ext = "";

		for (int i = 0; i < lv.getCount(); i++) {
			if (lv.isItemChecked(i)) {
				tempstring = tempstring + files[i];

				if (tempstring.length() > 1)
					ext = tempstring.substring(tempstring.lastIndexOf(".") + 1,
							tempstring.length());

				break;
			}
		}

		String filedate = tempstring.substring(tempstring.indexOf("-") + 1,
				tempstring.lastIndexOf("."));
		String tempstring_without_ext = tempstring.substring(0, tempstring
				.lastIndexOf("."));
		File[] userChoiceFiles = userChoiceFolder.listFiles();
		int t = userChoiceFiles.length;
		String latString = getFileLatitude(tempstring_without_ext);
		String lngString = getFileLongitude(tempstring_without_ext);
		String accString = getFileAccuracy(tempstring_without_ext);
		String tagsString = getFileTags(tempstring_without_ext);

		String string_for_file_name_change = rename_box.getText().toString()
				+ "-" + filedate;
		registerFilePrefs(string_for_file_name_change, latString, lngString,
				accString, tagsString);
		// Request.notification(myContext, "Debug", latString +
		// tempstring_without_ext + string_for_file_name_change);
		for (int j = 0; j < t; j++) {
			try {
				FileChannel channel = new RandomAccessFile(userChoiceFiles[j],
						"rw").getChannel();
				FileLock lock = channel.lock();
				try {
					lock = channel.tryLock();
				} catch (Exception e) {
				}

				if (userChoiceFiles[j].getName().equals(tempstring)) {
					userChoiceFiles[j].renameTo(new File(userChoiceFolder
							.getAbsoluteFile()
							+ "/"
							+ rename_box.getText().toString()
							+ "-"
							+ filedate + "." + ext));
					break;
				} else {
				}
				lock.release();
			} catch (Exception e) {
			}
		}

	}

	public void preview_File_Functionality() {
		ListView lv = getListView();
		String tempstring = new String();
		String ext = new String();
		String fileName = new String();
		for (int i = 0; i < lv.getCount(); i++) {
			if (lv.isItemChecked(i)) {
				tempstring = tempstring + files[i] + ",";

			}
		}

		if (tempstring.length() > 1)
			fileName = tempstring.substring(0, tempstring.lastIndexOf(","));
		// Request.notification( myContext ,"Playing sound", fileName);
		if (tempstring.length() > 1)
			tempstring = tempstring.substring(0, tempstring.lastIndexOf(","));
		if (tempstring.length() > 1)
			ext = tempstring.substring(tempstring.lastIndexOf(".") + 1,
					tempstring.length());
		fileName = "/sdcard/urbanremix/userchoice/" + fileName;
		if (ext.equals("wav")) {
			// Request.notification( myContext ,"Playing sound", ext);
			if (!playing) {
				try {
					// set the button text
					// Request.notification( myContext ,"Playing sound",
					// "Recently recorded "+wavio.getWavFileName());
					((android.widget.Button) findViewById(R.id.Preview))
							.setText(R.string.stop);
					startPlayback(fileName);
					playing = true;

				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalStateException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}
		if (ext.equals("jpg") || ext.equals("jpeg")) {
			// Request.notification(myContext, "Image", "just befor for +
			// tempstring);
			imagePreview.setVisibility(View.VISIBLE);
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inSampleSize = 10;
			bmImg = BitmapFactory.decodeFile(fileName, options);
			imagePreview.setImageBitmap(bmImg);
		}

	}

	public void startPlayback(String fileName) // throws
	// IllegalArgumentException,
	// IllegalStateException,
	// IOException
	{

		try {
			mp = new MediaPlayer();
			mp.setDataSource(fileName);
			// Request.notification( myContext ,"Playing sound", fileName);
			mp.prepare();
			mp.start();
			mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

				public void onCompletion(MediaPlayer mp) {
					((android.widget.Button) findViewById(R.id.Preview))
							.setText(R.string.preview);
					playing = false;
				}
			});
		} catch (Exception e) {
			Request.notification(this, "error", e.getMessage());
		}
	}

	public void stopPlayback() {
		mp.stop();
		mp.release();
	}

	public void upload_functionality() {
		if (!qUploader.isAlive()) {
			// Request.notification( myContext ,"hello","if");
			qUploader.start();
		}

	}

	public void registerFilePrefs(String filename, String latitude,
			String longitude, String accuracy, String tags) {
		int mode = Activity.MODE_PRIVATE;
		SharedPreferences mySharedPreferences = getSharedPreferences(
				"mySharedPreferences", mode);

		SharedPreferences.Editor editor = mySharedPreferences.edit();

		editor.putString(filename + "Latitude", latitude);
		editor.putString(filename + "Longitude", longitude);
		editor.putString(filename + "Accuracy", accuracy);
		editor.putString(filename + "Tags", tags);

		editor.commit();
	}

	// @return fileLatitude
	public String getFileLatitude(String filename) {
		int mode = Activity.MODE_PRIVATE;
		SharedPreferences mySharedPreferences = getSharedPreferences(MYPREFS,
				mode);
		return mySharedPreferences.getString(filename + "Latitude", "0.0");
	}

	// @return fileLongitude
	public String getFileLongitude(String filename) {
		int mode = Activity.MODE_PRIVATE;
		SharedPreferences mySharedPreferences = getSharedPreferences(MYPREFS,
				mode);
		return mySharedPreferences.getString(filename + "Longitude", "0.0");
	}

	// @return fileAccuracy
	public String getFileAccuracy(String filename) {
		int mode = Activity.MODE_PRIVATE;
		SharedPreferences mySharedPreferences = getSharedPreferences(MYPREFS,
				mode);
		return mySharedPreferences.getString(filename + "Accuracy", "0.0");
	}

	// @return fileTags
	public String getFileTags(String filename) {
		int mode = Activity.MODE_PRIVATE;
		SharedPreferences mySharedPreferences = getSharedPreferences(
				"mySharedPreferences", mode);
		return mySharedPreferences.getString(filename + "Tags", "");
	}

	// @return username
	public String getUsername() {
		int mode = Activity.MODE_PRIVATE;

		SharedPreferences mySharedPreferences = getSharedPreferences(
				"mySharedPreferences", mode);
		return mySharedPreferences.getString("username", "");

	}

	// @return password
	public String getPassword() {

		int mode = Activity.MODE_PRIVATE;

		SharedPreferences mySharedPreferences = getSharedPreferences(
				"mySharedPreferences", mode);

		return mySharedPreferences.getString("password", "");
	}

	public File getQueueFolder() {
		return this.queueFolder;
	}

	public File getTempFolder() {
		return this.tempFolder;
	}

	public void unregisterFilePrefs(String filename) {
		int mode = Activity.MODE_PRIVATE;
		SharedPreferences mySharedPreferences = getSharedPreferences(
				"mySharedPreferences", mode);

		SharedPreferences.Editor editor = mySharedPreferences.edit();

		editor.remove(filename + "Latitude");
		editor.remove(filename + "Longitude");
		editor.remove(filename + "Accuracy");
		editor.remove(filename + "Tags");

		editor.commit();
	}

	private Handler toastHandler = new Handler() {
		public void handleMessage(Message msg) {
			Bundle b = msg.getData();
			String msgString = b.getString("message");
			TextView tv = (TextView) findViewById(R.id.statusbar);
			tv.setVisibility(1);
			tv.setText(msgString);
			// Request.notification( myContext ,"Message",msgString);

		}
	};

	public Handler getHandler() {
		return this.toastHandler;
	}

	public String getFolderPath() {
		return this.folderPath;
	}

	public String getTempFolderPath() {
		return this.tempFolderPath;
	}

	public String getQueueFolderPath() {
		return this.queueFolderPath;
	}

}
